/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Isle;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Room;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.CoolingSystem;
import it.polimi.games.epkb.entityClasses.Rack;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class IsleJpaController implements Serializable {

    public IsleJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public IsleJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Isle isle) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (isle.getRackCollection() == null) {
            isle.setRackCollection(new ArrayList<Rack>());
        }
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = isle.getComponent();
        if (componentOrphanCheck != null) {
            Isle oldIsleOfComponent = componentOrphanCheck.getIsle();
            if (oldIsleOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type Isle whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Room IDRoom = isle.getIDRoom();
            if (IDRoom != null) {
                IDRoom = em.getReference(IDRoom.getClass(), IDRoom.getId());
                isle.setIDRoom(IDRoom);
            }
            Component component = isle.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                isle.setComponent(component);
            }
            CoolingSystem IDCoolingSystem = isle.getIDCoolingSystem();
            if (IDCoolingSystem != null) {
                IDCoolingSystem = em.getReference(IDCoolingSystem.getClass(), IDCoolingSystem.getId());
                isle.setIDCoolingSystem(IDCoolingSystem);
            }
            Collection<Rack> attachedRackCollection = new ArrayList<Rack>();
            for (Rack rackCollectionRackToAttach : isle.getRackCollection()) {
                rackCollectionRackToAttach = em.getReference(rackCollectionRackToAttach.getClass(), rackCollectionRackToAttach.getId());
                attachedRackCollection.add(rackCollectionRackToAttach);
            }
            isle.setRackCollection(attachedRackCollection);
            em.persist(isle);
            if (IDRoom != null) {
                IDRoom.getIsleCollection().add(isle);
                IDRoom = em.merge(IDRoom);
            }
            if (component != null) {
                component.setIsle(isle);
                component = em.merge(component);
            }
            if (IDCoolingSystem != null) {
                IDCoolingSystem.getIsleCollection().add(isle);
                IDCoolingSystem = em.merge(IDCoolingSystem);
            }
            for (Rack rackCollectionRack : isle.getRackCollection()) {
                Isle oldIDIsleOfRackCollectionRack = rackCollectionRack.getIDIsle();
                rackCollectionRack.setIDIsle(isle);
                rackCollectionRack = em.merge(rackCollectionRack);
                if (oldIDIsleOfRackCollectionRack != null) {
                    oldIDIsleOfRackCollectionRack.getRackCollection().remove(rackCollectionRack);
                    oldIDIsleOfRackCollectionRack = em.merge(oldIDIsleOfRackCollectionRack);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findIsle(isle.getId()) != null) {
                throw new PreexistingEntityException("Isle " + isle + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Isle isle) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Isle persistentIsle = em.find(Isle.class, isle.getId());
            Room IDRoomOld = persistentIsle.getIDRoom();
            Room IDRoomNew = isle.getIDRoom();
            Component componentOld = persistentIsle.getComponent();
            Component componentNew = isle.getComponent();
            CoolingSystem IDCoolingSystemOld = persistentIsle.getIDCoolingSystem();
            CoolingSystem IDCoolingSystemNew = isle.getIDCoolingSystem();
            Collection<Rack> rackCollectionOld = persistentIsle.getRackCollection();
            Collection<Rack> rackCollectionNew = isle.getRackCollection();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                Isle oldIsleOfComponent = componentNew.getIsle();
                if (oldIsleOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type Isle whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (IDRoomNew != null) {
                IDRoomNew = em.getReference(IDRoomNew.getClass(), IDRoomNew.getId());
                isle.setIDRoom(IDRoomNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                isle.setComponent(componentNew);
            }
            if (IDCoolingSystemNew != null) {
                IDCoolingSystemNew = em.getReference(IDCoolingSystemNew.getClass(), IDCoolingSystemNew.getId());
                isle.setIDCoolingSystem(IDCoolingSystemNew);
            }
            Collection<Rack> attachedRackCollectionNew = new ArrayList<Rack>();
            for (Rack rackCollectionNewRackToAttach : rackCollectionNew) {
                rackCollectionNewRackToAttach = em.getReference(rackCollectionNewRackToAttach.getClass(), rackCollectionNewRackToAttach.getId());
                attachedRackCollectionNew.add(rackCollectionNewRackToAttach);
            }
            rackCollectionNew = attachedRackCollectionNew;
            isle.setRackCollection(rackCollectionNew);
            isle = em.merge(isle);
            if (IDRoomOld != null && !IDRoomOld.equals(IDRoomNew)) {
                IDRoomOld.getIsleCollection().remove(isle);
                IDRoomOld = em.merge(IDRoomOld);
            }
            if (IDRoomNew != null && !IDRoomNew.equals(IDRoomOld)) {
                IDRoomNew.getIsleCollection().add(isle);
                IDRoomNew = em.merge(IDRoomNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setIsle(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setIsle(isle);
                componentNew = em.merge(componentNew);
            }
            if (IDCoolingSystemOld != null && !IDCoolingSystemOld.equals(IDCoolingSystemNew)) {
                IDCoolingSystemOld.getIsleCollection().remove(isle);
                IDCoolingSystemOld = em.merge(IDCoolingSystemOld);
            }
            if (IDCoolingSystemNew != null && !IDCoolingSystemNew.equals(IDCoolingSystemOld)) {
                IDCoolingSystemNew.getIsleCollection().add(isle);
                IDCoolingSystemNew = em.merge(IDCoolingSystemNew);
            }
            for (Rack rackCollectionOldRack : rackCollectionOld) {
                if (!rackCollectionNew.contains(rackCollectionOldRack)) {
                    rackCollectionOldRack.setIDIsle(null);
                    rackCollectionOldRack = em.merge(rackCollectionOldRack);
                }
            }
            for (Rack rackCollectionNewRack : rackCollectionNew) {
                if (!rackCollectionOld.contains(rackCollectionNewRack)) {
                    Isle oldIDIsleOfRackCollectionNewRack = rackCollectionNewRack.getIDIsle();
                    rackCollectionNewRack.setIDIsle(isle);
                    rackCollectionNewRack = em.merge(rackCollectionNewRack);
                    if (oldIDIsleOfRackCollectionNewRack != null && !oldIDIsleOfRackCollectionNewRack.equals(isle)) {
                        oldIDIsleOfRackCollectionNewRack.getRackCollection().remove(rackCollectionNewRack);
                        oldIDIsleOfRackCollectionNewRack = em.merge(oldIDIsleOfRackCollectionNewRack);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = isle.getId();
                if (findIsle(id) == null) {
                    throw new NonexistentEntityException("The isle with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Isle isle;
            try {
                isle = em.getReference(Isle.class, id);
                isle.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The isle with id " + id + " no longer exists.", enfe);
            }
            Room IDRoom = isle.getIDRoom();
            if (IDRoom != null) {
                IDRoom.getIsleCollection().remove(isle);
                IDRoom = em.merge(IDRoom);
            }
            Component component = isle.getComponent();
            if (component != null) {
                component.setIsle(null);
                component = em.merge(component);
            }
            CoolingSystem IDCoolingSystem = isle.getIDCoolingSystem();
            if (IDCoolingSystem != null) {
                IDCoolingSystem.getIsleCollection().remove(isle);
                IDCoolingSystem = em.merge(IDCoolingSystem);
            }
            Collection<Rack> rackCollection = isle.getRackCollection();
            for (Rack rackCollectionRack : rackCollection) {
                rackCollectionRack.setIDIsle(null);
                rackCollectionRack = em.merge(rackCollectionRack);
            }
            em.remove(isle);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Isle> findIsleEntities() {
        return findIsleEntities(true, -1, -1);
    }

    public List<Isle> findIsleEntities(int maxResults, int firstResult) {
        return findIsleEntities(false, maxResults, firstResult);
    }

    private List<Isle> findIsleEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Isle.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Isle findIsle(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Isle.class, id);
        } finally {
            em.close();
        }
    }

    public int getIsleCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Isle> rt = cq.from(Isle.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
